﻿using System;
using System.Text.RegularExpressions;
using System.Web.Mvc;
using BSF.Db;
using BSF.Enums;
using BSF.Log;
using BSF.ServicesResult;
using BSF.SystemConfig;
using BSF.Tool;
using HuntingFishGame.Domain.BLL.WeChat;
using HuntingFishGame.Domain.Model.WeChat;
using Newtonsoft.Json;

namespace HuntingFishGame.CustomerApi.Controllers
{
    /// <summary>
    /// 微信授权API接口
    /// </summary>
    public class WeChatController : BaseApiController
    {
        // 微信认证首页
        public ActionResult Index(string xx = "", string gourl = "")
        {
            // 此页面引导用户点击授权
            try
            {
                // 授权登录页
                //WeChatConfigModel config = null;
                //WeixinConfig.GetAppIDSecret(ref config);
                string urlUserInfo = WeChatUrlBLL.GetAuthorizeUrl(WeixinConfig.AppId(WeixinType.CertServiceAccount), WeixinConfig.SiteHost.TrimEnd('/') + "/WeChat/UserInfoCallback?xx=" + xx + "&gourl=" + System.Web.HttpUtility.UrlEncode(gourl), WeixinConfig.TmpRandomState_1, OAuthScope.snsapi_userinfo);

                // 注：静默跳转，适用于已经登录过，下次去微信重新获取信息或刷新token
                string urlBase = WeChatUrlBLL.GetAuthorizeUrl(WeixinConfig.AppId(WeixinType.CertServiceAccount), WeixinConfig.SiteHost.TrimEnd('/') + "/WeChat/BaseCallback?xx=" + xx + "&gourl=" + System.Web.HttpUtility.UrlEncode(gourl), WeixinConfig.TmpRandomState_2, OAuthScope.snsapi_base);

                //ViewBag.urlUserInfo = urlUserInfo;
                //ViewBag.urlBase = urlBase;
                //return Content(string.Format("<h1>测试页<a href=\"{0}\"></a></h1>", Url.Action("Test", "OAuth2", new { area = string.Empty })));

                // 正常模式：直接跳转到微信的授权登录页
                return Redirect(urlBase);
            }
            catch (Exception ex)
            {
                return Content("发生错误：" + ex.Message);
            }
        }

        /// <summary>
        /// 授权方式回调(登录授权)
        /// </summary>
        /// <param name="code"></param>
        /// <param name="state"></param>
        /// <param name="xx"></param>
        /// <param name="gourl"></param>
        /// <param name="scan">是否扫码进入（0否，1是）</param>
        /// <returns></returns>
        public ActionResult UserInfoCallback(string code, string state, string xx = "", string gourl = "", int scan = 0)
        {
            CommLog.Write("回调(UserInfoCallback):" + code);
            bool isValied = !string.IsNullOrEmpty(code)
                        && !string.IsNullOrEmpty(state) && (state.Equals(WeixinConfig.TmpRandomState_1) || state.Equals(WeixinConfig.TmpRandomState_2));

            if (isValied)
            {
                //ownerid = ownerid.HasValue ? ownerid : Guid.Empty;//ownerid = ownerid ?? Guid.Empty;
                // 通过code换取用户授权
                OAuthUserInfo userOAuthInfo = null;
                UnionUserInfo userInfo = null;//获取用户信息接口
                //获取网页授权access_token（调用次数限制:无）。这里通过code换取的是一个特殊的网页授权access_token,与基础支持中的access_token（该access_token用于调用其他接口）不同
                OAuthAccessTokenResult userToken = WeChatUrlBLL.GetUserAccessToken(WeixinConfig.AppId(WeixinType.CertServiceAccount), WeixinConfig.AppSecret(WeixinType.CertServiceAccount), code);
                if (userToken != null && userToken.CheckIsSuccess())
                {
                    //保存网页授权access_token,refresh_token(由于access_token拥有较短的有效期，当access_token超时后，可以使用refresh_token进行刷新，refresh_token有效期为30天，当refresh_token失效之后，需要用户重新授权。)
                    //因为网页授权access_token次数不限制，所以暂时不保存

                    // 更新用户微信登录信息
                    //long userId;
                    #region 用户微信登录信息处理
                    //取授权用户信息
                    userOAuthInfo = WeChatUrlBLL.GetOAuthUserInfo(userToken.access_token, userToken.openid);
                    //获取用户信息接口(前提:必须要关注公众号)
                    userInfo = WeChatUrlBLL.GetUnionUserInfo(WeixinConfig.BaseAccessToken(WeixinType.CertServiceAccount).ParamValue, userToken.openid);
                    //Session["MyOpenId"] = userToken.openid;

                    WechatFollowModel modelWechat = null;
                    modelWechat = WeChatFollowBLL.GetModelDetail(BSFConfig.MainConnectString, userToken.openid);

                    if (modelWechat != null)
                    {
                        #region 更新用户微信登录信息
                        modelWechat.Updatecs += 1;
                        modelWechat.UpdateTime = DateTime.Now;
                        modelWechat.NickName = string.IsNullOrEmpty(userOAuthInfo.nickname) == true ? "" : userOAuthInfo.nickname;
                        modelWechat.HeadImgUrl = userOAuthInfo.headimgurl;
                        modelWechat.IsSubscribe = userInfo != null && userInfo.subscribe == 1 ? true : false;//是否关注,如果关注，则可以根据获取用户基本信息接口取用户信息
                        //注册，登录时微信绑定用户
                        //if (ownerid.Value != Guid.Empty)
                        //    modelWechat.UserId = ownerid.Value;
                        WeChatFollowBLL.Update(BSFConfig.MainConnectString, modelWechat);
                        #endregion
                    }
                    else
                    {
                        #region 新增用户微信登录信息
                        modelWechat = new WechatFollowModel();
                        modelWechat.AppId = WeixinConfig.AppId(WeixinType.CertServiceAccount);
                        modelWechat.OpenId = userToken.openid;
                        modelWechat.OauthScope = userToken.scope;
                        modelWechat.IsAuth = userToken.scope.Contains("snsapi_userinfo") == true ? true : false;
                        modelWechat.IsSubscribe = userInfo != null && userInfo.subscribe == 1 ? true : false;//是否关注,如果关注，则可以根据获取用户基本信息接口取用户信息
                        modelWechat.NickName = string.IsNullOrEmpty(userOAuthInfo.nickname) == true ? "" : userOAuthInfo.nickname;
                        modelWechat.Sex = userOAuthInfo.sex;
                        modelWechat.Province = userOAuthInfo.province;
                        modelWechat.City = userOAuthInfo.city;
                        modelWechat.Country = userOAuthInfo.country;
                        modelWechat.HeadImgUrl = userOAuthInfo.headimgurl;
                        modelWechat.UnionId = userOAuthInfo.unionid ?? "";
                        modelWechat.Privilege = userOAuthInfo.privilege == null
                            ? ""
                            : string.Join(",", userOAuthInfo.privilege);
                        //modelWechat.language = userInfo.language;
                        modelWechat.CreateTime = DateTime.Now;
                        modelWechat.UpdateTime = DateTime.MinValue;
                        modelWechat.Updatecs = 0;
                        //注册，登录时微信绑定用户
                        //if (ownerid.Value != Guid.Empty)
                        //    modelWechat.UserId = ownerid.Value;
                        //记录微信关注授权信息
                        WeChatFollowBLL.Add(BSFConfig.MainConnectString, modelWechat);
                        #endregion
                    }
                    #endregion

                    //获取Token
                    var user = ApiUtils.Login(modelWechat.OpenId, modelWechat.NickName, 0, 0, DeviceTypeEnum.Web);

                    //TODO 跳转到首页
                    if (string.IsNullOrEmpty(gourl))
                    {
                        return RedirectToAction("Index", "Home", new { area = string.Empty });
                    }

                    else
                    {
                        gourl = System.Web.HttpUtility.UrlDecode(gourl);
                        var pattern = @"(\w+)=(\w+)";
                        Regex urlRegex = new Regex(pattern);
                        Match m = urlRegex.Match(gourl.ToLower());
                        if (m.Success)
                        {
                            return Redirect(gourl + "&token=" + user.Token);
                        }
                        else
                        {
                            return Redirect(gourl + "?token=" + user.Token);
                        }
                    }
                }
                else
                {
                    throw new Exception("授权获取令牌失败(" + userToken.errcode + ")：" + userToken.errmsg);
                }
                //return RedirectToAction("Index", "Home", new { area = string.Empty });
            }
            else
            {
                throw new Exception("授权验证失败");
            }


        }

        /// <summary>
        /// 授权方式回调(静默授权)
        /// </summary>
        /// <param name="code"></param>
        /// <param name="state"></param>
        /// <param name="xx"></param>
        /// <param name="gourl"></param>
        /// <param name="scan">是否扫码进入（0否，1是）</param>
        /// <returns></returns>
        public ActionResult BaseCallback(string code, string state, string xx = "", string gourl = "", int scan = 0)
        {
            #region 静默授权数据处理
            //验证
            bool isValied = !string.IsNullOrEmpty(code)
                        && !string.IsNullOrEmpty(state) && (state.Equals(WeixinConfig.TmpRandomState_1) || state.Equals(WeixinConfig.TmpRandomState_2));

            if (isValied)
            {
                OAuthUserInfo userOAuthInfo = null;
                UnionUserInfo userInfo = null;//高级信息接口
                OAuthAccessTokenResult userToken = WeChatUrlBLL.GetUserAccessToken(WeixinConfig.AppId(WeixinType.CertServiceAccount), WeixinConfig.AppSecret(WeixinType.CertServiceAccount), code);
                if (userToken != null && userToken.CheckIsSuccess())
                {
                    #region 用户微信登录信息处理
                    userOAuthInfo = WeChatUrlBLL.GetOAuthUserInfo(userToken.access_token, userToken.openid);
                    //Session["MyOpenId"] = userToken.openid;
                    //WebHelper.SetCookie("openid", userToken.openid, 24);//openid存储

                    //高级信息接口                    
                    userInfo = WeChatUrlBLL.GetUnionUserInfo(WeixinConfig.BaseAccessToken(WeixinType.CertServiceAccount).ParamValue, userToken.openid);

                    WechatFollowModel modelWechat = null;
                    modelWechat = WeChatFollowBLL.GetModelDetail(BSFConfig.MainConnectString, userToken.openid);

                    if (modelWechat != null)
                    {
                        #region 更新用户微信登录信息
                        modelWechat.Updatecs += 1;
                        modelWechat.UpdateTime = DateTime.Now;
                        modelWechat.NickName = string.IsNullOrEmpty(userOAuthInfo.nickname) == true ? "" : userOAuthInfo.nickname;
                        modelWechat.HeadImgUrl = userOAuthInfo.headimgurl;
                        modelWechat.IsSubscribe = userInfo != null && userInfo.subscribe == 1 ? true : false;//是否关注,如果关注，则可以根据获取用户基本信息接口取用户信息
                        //注册，登录时微信绑定用户
                        //if (ownerid.Value != Guid.Empty)
                        //    modelWechat.UserId = ownerid.Value;
                        WeChatFollowBLL.Update(BSFConfig.MainConnectString, modelWechat);
                        #endregion
                    }
                    else
                    {
                        #region 新增用户微信登录信息
                        modelWechat = new WechatFollowModel();
                        modelWechat.AppId = WeixinConfig.AppId(WeixinType.CertServiceAccount);
                        modelWechat.OpenId = userToken.openid;
                        modelWechat.OauthScope = userToken.scope;
                        modelWechat.IsAuth = userToken.scope.Contains("snsapi_userinfo") == true ? true : false;
                        modelWechat.IsSubscribe = userInfo != null && userInfo.subscribe == 1 ? true : false;//是否关注,如果关注，则可以根据获取用户基本信息接口取用户信息
                        modelWechat.NickName = string.IsNullOrEmpty(userOAuthInfo.nickname) == true ? "" : userOAuthInfo.nickname;
                        modelWechat.Sex = userOAuthInfo.sex;
                        modelWechat.Province = userOAuthInfo.province;
                        modelWechat.City = userOAuthInfo.city;
                        modelWechat.Country = userOAuthInfo.country;
                        modelWechat.HeadImgUrl = userOAuthInfo.headimgurl;
                        modelWechat.UnionId = userOAuthInfo.unionid ?? "";
                        modelWechat.Privilege = userOAuthInfo.privilege == null
                            ? ""
                            : string.Join(",", userOAuthInfo.privilege);
                        //modelWechat.language = userInfo.language;
                        modelWechat.CreateTime = DateTime.Now;
                        modelWechat.UpdateTime = DateTime.MinValue;
                        modelWechat.Updatecs = 0; 
                        //注册，登录时微信绑定用户
                        //if (ownerid.Value != Guid.Empty)
                        //    modelWechat.UserId = ownerid.Value;
                        //记录微信关注授权信息
                        WeChatFollowBLL.Add(BSFConfig.MainConnectString, modelWechat);
                        #endregion
                    }
                    #endregion

                    //获取Token
                    var user = ApiUtils.Login(modelWechat.OpenId, modelWechat.NickName, 0, 0, DeviceTypeEnum.Web);

                    if (string.IsNullOrEmpty(gourl))
                    {
                        return RedirectToAction("Index", "Home", new { area = string.Empty });
                    }

                    else
                    {
                        gourl = System.Web.HttpUtility.UrlDecode(gourl);
                        var pattern = @"(\w+)=(\w+)";
                        Regex urlRegex = new Regex(pattern);
                        Match m = urlRegex.Match(gourl.ToLower());
                        if (m.Success)
                        {
                            return Redirect(gourl + "&token=" + user.Token);
                        }
                        else
                        {
                            return Redirect(gourl + "?token=" + user.Token);
                        }
                    }
                }
                else
                {
                    return Content("参数错误");
                }
            }
            else
            {
                return Content("参数错误");
            }
            #endregion
        }

        /// <summary>
        /// 发送微信模版信息
        /// </summary>
        /// <param name="openId"></param>
        /// <param name="verifyCode">验证码</param>
        /// <returns></returns>
        public ActionResult SendWeChatTemplateMsg(string openId, string verifyCode)
        {
            return this.Visit(UserTypeEnum.none, (token) =>
            {
                string accesstoken = WeixinConfig.BaseAccessToken(WeixinType.CertServiceAccount).ParamValue;
                //改成自己的获取ACCESS_TOKEN的方法

                var data = new
                {
                    //使用TemplateDataItem简单创建数据。
                    verifyCode = new
                    {
                        //使用new 方式，构建数据，包括value, color两个固定属性。
                        value = verifyCode + "\n",
                        color = "#173177"
                    },
                    arrivedTime = new
                    {
                        //使用new 方式，构建数据，包括value, color两个固定属性。
                        value = DateTime.Now.ToString("yyyy年MM月dd日") + "\n",
                        color = "#173177"
                    },
                    remark = new
                    {
                        //使用new 方式，构建数据，包括value, color两个固定属性。
                        value = "如非本人操作，请尽快修改密码。【鱼乐游戏】\n",
                        color = "#173177"
                    }
                };
                string dataStr = Newtonsoft.Json.JsonConvert.SerializeObject(data);
                var template = JsonConvert.DeserializeObject<WeChatTemplateModel>(BSFConfig.WeChatTemplate);
                string templateId = template.TemplateId; //这个是模拟测试的模板编号。。正式的用方法去微信获取
                string url = template.TemplateUrl;
                string topColor = template.TopColor;
                var response = WeChatSendMessageHelper.SendTemplateMessage(accesstoken, openId, templateId, data, url, topColor);
                if (response.errcode > -1)
                {
                    return new ServiceResult { code = (int)BSFAPICode.Success, data = response.data };
                }
                else
                {
                    ErrorLog.Write("发送模版消息失败" + JsonConvert.SerializeObject(response), null);
                    return new ServiceResult { code = (int)BSFAPICode.NormalError, data = true, msg = response.errmsg };
                }
            });
        }


    }
}